//
//  ChenJianViewController.m
//  PDA巡检
//
//  Created by Vencoo on 14-2-27.
//  Copyright (c) 2014年 Vencoo. All rights reserved.
//

#import "ChenJianViewController.h"

@interface ChenJianViewController ()
{
    NSMutableArray *sendControls;
    NSMutableArray *childIds;
    UIImage *roundSelect;
    UIImage *roundUnselect;
}
@end

@implementation ChenJianViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    NSArray *queryDataArr = [NSArray array];
    self.title = @"日常晨检";
    queryDataArr = @[
                     @{@"id": @"1",@"floorname":@"9F",@"rfid":@"<#string#>"},
                     @{@"id": @"2",@"floorname":@"8F",@"rfid":@"<#string#>"},
                     @{@"id": @"3",@"floorname":@"7F",@"rfid":@"<#string#>"},
                     @{@"id": @"4",@"floorname":@"6F",@"rfid":@"<#string#>"},
                     @{@"id": @"5",@"floorname":@"5F",@"rfid":@"<#string#>"},
                     @{@"id": @"6",@"floorname":@"4F",@"rfid":@"<#string#>"},
                     @{@"id": @"7",@"floorname":@"3F",@"rfid":@"<#string#>"},
                     @{@"id": @"8",@"floorname":@"2F",@"rfid":@"<#string#>"},
                     @{@"id": @"9",@"floorname":@"1F",@"rfid":@"<#string#>"},
                     @{@"id": @"10",@"floorname":@"裙6",@"rfid":@"<#string#>"},
                     @{@"id": @"11",@"floorname":@"裙5",@"rfid":@"<#string#>"},
                     @{@"id": @"12",@"floorname":@"裙4",@"rfid":@"<#string#>"},
                     @{@"id": @"13",@"floorname":@"裙3",@"rfid":@"<#string#>"},
                     @{@"id": @"14",@"floorname":@"裙2",@"rfid":@"<#string#>"},
                     @{@"id": @"15",@"floorname":@"裙1",@"rfid":@"<#string#>"},
                     @{@"id": @"16",@"floorname":@"其它",@"rfid":@"<#string#>"}];
    self.sendUrl = addChenjian;
    [super viewDidLoad];
    sendControls = [NSMutableArray array];
    childIds = [NSMutableArray array];

    self.floorNames = [NSMutableArray array];
    [self.floorIds removeAllObjects];
    for (NSDictionary *dic in queryDataArr)
    {
        [self.floorNames addObject:[dic valueForKey:@"floorname"]];
        [self.floorIds addObject:[dic valueForKey:@"id"]];
        [self.sendFloorDatas addObject:@""];
        [self.xunJianCellInfos addObject:@{@"hidden":@"1",@"floorId":[dic valueForKey:@"id"] }];
    }
    [self initData];
    [self showUIWithArray:self.allShowDataArr andFloorId:@"1"];
    
    NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.myTableView selectRowAtIndexPath:index animated:YES scrollPosition:UITableViewScrollPositionMiddle];
}
- (void)initData
{
    roundSelect = [UIImage imageNamed:@"选中"];
    roundUnselect = [UIImage imageNamed:@"未选中"];
    NSDictionary *oneDic = @{@"checkId": @"1",@"checkName":@"大堂公共区域",@"children":@[@"1、照明",@"2、电子显示屏",@"3、自动门（平移、旋转）",@"4、电梯（高、中、低区）",@"5、告示牌放置（内容）",@"6、清洁状况",@"7、绿化摆放",@"8、空调温度",@"9、标牌系统"]};
    NSDictionary *twoDic = @{@"checkId": @"2",@"checkName":@"1~9F主楼、裙楼",@"children":@[@"1、照明",@"2、空调温度",@"3、标牌系统",@"4、清洁状况",@"5、通排风",@"6、开水器",@"7、生饮机",@"8、皂液盒",@"9、烘干机",@"10、洁具"]};
    NSDictionary *ThreeDic = @{@"checkId": @"3",@"checkName":@"二次装修",@"children":@[@"1、楼层/单元状况",@"2、施工情况",@"3、施工人员情况"]};
    NSDictionary *fourDic = @{@"checkId": @"4",@"checkName":@"风雨天气的特殊措施",@"children":@[@"1、防滑标志设置",@"2、套伞设备放置",@"3、外围绿摆保护",@"4、防滑地毯"]};
    NSDictionary *fiveDic = @{@"checkId": @"5",@"checkName":@"大厦外围",@"children":@[@"1、绿化养护情况",@"2、旗杆栏杆",@"3、喷水池",@"4、外围设施"]};
    NSDictionary *sixDic = @{@"checkId": @"6",@"checkName":@"情况讯问（中控）",@"children":@[@"1、昨夜大厦运行情况",@"2、回收前日加时空调、新风申请表"]};
    self.allShowDataArr = @[oneDic,twoDic,ThreeDic,fourDic,fiveDic,sixDic];
    int childNumId = 0;
    for (int i = 0; i < self.allShowDataArr.count; i ++)
    {
        NSMutableArray *InnerChildIds = [NSMutableArray array];
        for (int j = 0; j < [self.allShowDataArr[i][@"children"] count]; j ++)
        {
            childNumId ++;
            [InnerChildIds addObject:[NSString stringWithFormat:@"%d",childNumId]];
        }
        [childIds addObject:InnerChildIds];
    }
}
- (void)showUIWithArray:(NSArray *)array andFloorId:(NSString *)floorId
{
    [self clearAll];
    self.floorIdQuanju = floorId;
    BOOL hasReserved = 0;
    NSArray *showDatas = [NSArray array];
    self.sendCheckDatas = [NSMutableArray array];
    [sendControls removeAllObjects];
    id receiveFloorObj = [self.sendFloorDatas objectAtIndex:[self.floorIds indexOfObjectss:self.floorIdQuanju]];
    if (![receiveFloorObj isKindOfClass:[NSString class]])
    {
        hasReserved = 1;
        self.sendCheckDatas = [receiveFloorObj objectForKey:@"checkData"];
    }
    else
    {
        int childNumId = 0;
        for (int i = 0; i < array.count; i ++)
        {
            NSMutableArray *childArr = [NSMutableArray array];
            NSMutableArray *InnerChildIds = [NSMutableArray array];
            for (int j = 0; j < [array[i][@"children"] count]; j ++)
            {
                childNumId ++;
                [childArr addObject:@{@"childId": [NSString stringWithFormat:@"%i",childNumId],@"isNormal":@"3",@"childRemark":@""}];
            }
            [self.sendCheckDatas addObject:@{@"checkId": [NSString stringWithFormat:@"%i",i+1],@"childData":childArr}];
        }
    }
    int childIdNum = 0;
    showDatas = array;
    if ([floorId integerValue] != 9 && [floorId integerValue] != 16)
    {
        NSMutableIndexSet *index = [NSMutableIndexSet indexSetWithIndexesInRange:NSMakeRange(1, 2)];
        showDatas = [array objectsAtIndexes:index];
        childIdNum = 9;
    }
    else if ([floorId integerValue] == 16)
    {
        showDatas = [array objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(3, 3)]];
        childIdNum = 22;
    }
    for (int i = 0; i < showDatas.count; i ++)
    {
        NSDictionary *dictionary = [showDatas objectAtIndex:i];
        NSString *checkID = [dictionary valueForKey:@"checkId"];
        NSString *checkName = [dictionary valueForKey:@"checkName"];
        NSArray *children = [dictionary objectForKey:@"children"];
        NSMutableArray *sendChildDatas = [NSMutableArray array];
        [self addCheckNames:checkName];
        NSMutableArray *tfs = [NSMutableArray array];
        NSMutableArray *btns = [NSMutableArray array];
        
        for (int j = 0; j < children.count; j ++)
        {
            childIdNum ++;
            int childIdIndex = [self indexOfObject:[NSString stringWithFormat:@"%i",childIdNum] Array:childIds];
            if (hasReserved)
            {
                sendChildDatas = self.sendCheckDatas[childIdIndex][@"childData"];
            }
            else
            {
                [sendChildDatas addObject:@{@"childId": [NSString stringWithFormat:@"%d",childIdNum],@"isNormal":@"0",@"childRemark":@""}];
            }
            NSString *childName = [children objectAtIndex:j];
            UILabel *childLb = [UILabel new];
            childLb.text = childName;
            childLb.font = [UIFont systemFontOfSize:25];
            CGSize mySz = [childLb.text sizeWithFont:childLb.font constrainedToSize:CGSizeMake(MAXFLOAT, 40)];
            childLb.frame = CGRectMake(60, [[self.checkNameLbs lastObject]frame].origin.y + [[self.checkNameLbs lastObject]frame].size.height + interval111*(j+1) + (interval111 + mySz.height)*4*j , mySz.width, mySz.height);
            [self.backScrollV addSubview:childLb];
            [self.controlWillClears addObject:childLb];
            [self.childLabels addObject:childLb];
            if (hasReserved)
            {
                [self addVerticalChildName:@[@"正常",@"一般问题",@"严重问题"] andCheckId:checkID andResult:[[sendChildDatas objectAtIndex:j]valueForKey:@"isNormal"]];
            }
            else
            {
                [self addVerticalChildName:@[@"正常",@"一般问题",@"严重问题"] andCheckId:checkID andResult:@"0"];
            }
            [btns addObject: self.selectBtnArr];
            
            UILabel *remarkLb = [UILabel new];
            remarkLb.text = @"备注：";
            remarkLb.font = [UIFont systemFontOfSize:25];
            mySz = [remarkLb.text sizeWithFont:remarkLb.font constrainedToSize:CGSizeMake(MAXFLOAT, 40)];
            remarkLb.frame = CGRectMake(100, [[self.controlWillClears lastObject]frame].origin.y + [[self.controlWillClears lastObject]frame].size.height + interval111, mySz.width, mySz.height);
            [self.backScrollV addSubview:remarkLb];
            [self.controlWillClears addObject:remarkLb];
            
            UITextField *tf = [[UITextField alloc]initWithFrame:CGRectMake(190, remarkLb.frame.origin.y, 340, mySz.height)];
            tf.delegate = self;
            if (hasReserved)
            {
                tf.text = [[[sendChildDatas objectAtIndex:j]valueForKey:@"childRemark"]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            }
            tf.background = [UIImage imageNamed:@"输入框底"];
            [self.backScrollV addSubview:tf];
            [self.controlWillClears addObject:tf];
            [tfs addObject:tf];
         }
        [sendControls addObject:@{@"checkId": checkID,@"childControls":tfs,@"childBtns":btns,@"childData":sendChildDatas}];
    }
    
    if (hasReserved)
    {
        [self addCommentKuang:[receiveFloorObj objectForKey:@"floorRemark"]];
    }
    else
    {
        [self addCommentKuang:@""];
    }
}
- (void)addCheckNames:(NSString*)string
{
    UILabel *checkNameLb = [UILabel new];
    checkNameLb.text = [NSString stringWithFormat:@"%@：",string];
    checkNameLb.font = [UIFont systemFontOfSize:26];
    CGSize mySize = [checkNameLb.text sizeWithFont:checkNameLb.font constrainedToSize:CGSizeMake(MAXFLOAT, 40)];
    if (self.controlWillClears.count != 0)
    {
        checkNameLb.frame = CGRectMake(10, interval111+([[self.controlWillClears lastObject]frame].origin.y + [[self.controlWillClears lastObject]frame].size.height), mySize.width, mySize.height);
    }
    else
    {
        checkNameLb.frame = CGRectMake(10, 10, mySize.width, mySize.height);
    }
    [self.backScrollV addSubview:checkNameLb];
    [self.checkNameLbs addObject:checkNameLb];
    [self.controlWillClears addObject:checkNameLb];
}

- (void)addVerticalChildName:(NSArray *)array andCheckId:(NSString *)checkId andResult:(NSString *)result
{
    NSMutableArray *controlsArr = [NSMutableArray array];
    self.selectBtnArr = [NSMutableArray array];
    for (int i = 0; i<array.count; i++)
    {
        UIButton *roundBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [roundBtn setImage:roundUnselect forState:UIControlStateNormal];
        if ([result isEqualToString:[NSString stringWithFormat:@"%i",i]]) {
            [roundBtn setImage:roundSelect forState:UIControlStateNormal];
        }
        [roundBtn addTarget:self action:@selector(selectBtns:) forControlEvents:UIControlEventTouchUpInside];
        roundBtn.tag = 10+i;
        roundBtn.frame = CGRectMake([[self.childLabels lastObject]frame].origin.x + 52, [[self.childLabels lastObject]frame].origin.y  - 4 + ([[self.childLabels lastObject]frame].size.height + 10)*(i+1) , roundUnselect.size.width, roundUnselect.size.height);
        [self.backScrollV addSubview:roundBtn];
        [self.controlWillClears addObject:roundBtn];
        [controlsArr addObject:roundBtn];
        
        UIImage *iconImage = [UIImage imageNamed:@""];
        switch (i)
        {
            case 0:
            {
                iconImage = [UIImage imageNamed:@"正常"];
            }
                break;
            case 1:
            {
                iconImage = [UIImage imageNamed:@"一般问题"];
            }
                break;
            case 2:
            {
                iconImage = [UIImage imageNamed:@"重大问题"];
            }
                break;
                
            default:
                break;
        }
        
        UIImageView *iconView = [[UIImageView alloc]initWithImage:iconImage];
        [iconView setFrame:CGRectMake([[self.childLabels lastObject]frame].origin.x + 52 + roundUnselect.size.width, [[self.childLabels lastObject]frame].origin.y + ([[self.childLabels lastObject]frame].size.height + 10)*(i+1) + 4, iconImage.size.width, iconImage.size.height)];
        [self.backScrollV addSubview:iconView];
        [self.controlWillClears addObject:iconView];
        
        UILabel *childLabel = [UILabel new];
        NSString *string = [array objectAtIndex:i];
        childLabel.text = [NSString stringWithFormat:@"%@：",string];
        childLabel.font = [UIFont systemFontOfSize:26];
        CGSize mySize = [childLabel.text sizeWithFont:childLabel.font constrainedToSize:CGSizeMake(MAXFLOAT, 40)];
        childLabel.frame = CGRectMake([[self.childLabels lastObject]frame].origin.x + roundUnselect.size.width + 52 + iconImage.size.width + 10, [[self.childLabels lastObject]frame].origin.y + ([[self.childLabels lastObject]frame].size.height + 10)*(i+1), mySize.width, mySize.height);
        [self.backScrollV addSubview:childLabel];
        [self.controlWillClears addObject:childLabel];
    }
    [self.selectBtnArr addObject:controlsArr];
}


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.myTableView)
    {
        return self.floorNames.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    [super tableView:tableView cellForRowAtIndexPath:indexPath];
    if (tableView == self.myTableView)
    {
        self.mycell.textLabel.text = [self.floorNames objectAtIndex:indexPath.row];
        return self.mycell;
    }
    return nil;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [super tableView:tableView didSelectRowAtIndexPath:indexPath];
    [self hiddenAll];
    if (tableView == self.myTableView)
    {
        [UIView animateWithDuration:.9 animations:^
         {
             self.backScrollV.contentSize = CGSizeMake(0, 0);
         }];
        
        [self showUIWithArray:self.allShowDataArr andFloorId:[self.floorIds objectAtIndex:indexPath.row]];
        self.floorIdQuanju = [self.floorIds objectAtIndex:indexPath.row];
        
    }
}
#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    for (int i = 0; i < sendControls.count; i ++)
    {
        NSDictionary *controlDic = [sendControls objectAtIndex:i];
        NSArray *tfs = [controlDic objectForKey:@"childControls"];
        NSMutableArray *sendChildDatas = [controlDic objectForKey:@"childData"];
        for (int j = 0; j < tfs.count; j ++)
        {
            NSDictionary *sendChildDic = [sendChildDatas objectAtIndex:j];
            NSString *isNormal = [sendChildDic valueForKey:@"isNormal"];
            id tf = [tfs objectAtIndex:j];
            if (tf == textField && [isNormal integerValue] != 0)
            {
                return YES;
            }
        }
    }
    return 0;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    
    for (int i = 0; i < sendControls.count; i ++)
    {
        NSDictionary *controlDic = [sendControls objectAtIndex:i];
        NSString *checkId = [controlDic valueForKey:@"checkId"];
        NSArray *tfs = [controlDic objectForKey:@"childControls"];
        NSMutableArray *sendChildDatas = [controlDic objectForKey:@"childData"];
        for (int j = 0; j < tfs.count; j ++)
        {
            NSDictionary *sendChildDic = [sendChildDatas objectAtIndex:j];
            NSString *childId = [sendChildDic valueForKey:@"childId"];
            NSString *isNormal = [sendChildDic valueForKey:@"isNormal"];
            NSString *remark = @"";
            id tf = [tfs objectAtIndex:j];
            if (tf == textField)
            {
                remark = [textField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                [sendChildDatas replaceObjectAtIndex:j withObject:@{@"childId": childId,@"isNormal":isNormal,@"childRemark":remark}];
//                int checkIdIndex = [self indexOfObject:childId Array:childIds];
//                int childIdIndex = [childIds[checkIdIndex] indexOfObject:childId];
                NSLog( @"%@",self.sendCheckDatas);
//                [self.sendCheckDatas replaceObjectAtIndex:childIdIndex withObject:@{@"checkId": checkId,@"childData":sendChildDatas}];
//                NSLog( @"%@",self.sendCheckDatas);
            }
        }
    }
}

#pragma mark - button action
- (void)selectBtns:(id)sender//运作部
{
    UIButton *btn = (UIButton*)sender;
    NSMutableArray *sendChildDatas = [NSMutableArray array];
    NSString *checkId = @"";
    int childIdNum = 0;
    if (![self.floorIdQuanju isEqualToString:@"9"] && [self.floorIdQuanju integerValue] != 16)
    {
        childIdNum = 9;
    }
    else if ([self.floorIdQuanju integerValue] == 16)
    {
        childIdNum = 22;
    }
    for (int a = 0; a<sendControls.count; a++)
    {
        NSDictionary *controlDic = [sendControls objectAtIndex:a];
//        NSDictionary *dataDic = [self.sendCheckDatas objectAtIndex:a];
        NSArray *btns = [controlDic valueForKey:@"childBtns"];
        for (int i = 0; i < btns.count ; i++)
        {
            NSArray *btnArr = [btns objectAtIndex:i];
            for (int j = 0; j < btnArr.count ; j++)
            {
                childIdNum ++;
                NSArray *lastBtnArr = [btnArr objectAtIndex:j];
                if ([lastBtnArr containsObject:btn])
                {
                    checkId = [controlDic valueForKey:@"checkId"];
                    sendChildDatas = [controlDic objectForKey:@"childData"];
                    for (int k = 0; k < lastBtnArr.count; k++)
                    {
                        NSDictionary *childDic = [sendChildDatas objectAtIndex:i];
                        //                        NSString *childId = [childDic objectForKey:@"childId"];
                        NSString *childRemark = [childDic objectForKey:@"childRemark"];
                        UIButton *seleBtn = [lastBtnArr objectAtIndex:k];
                        [seleBtn setImage:self.roundUnselect forState:UIControlStateNormal];
                        int checkIdIndex = 0;
                        int childIdIndex = 0;
                        if (btn == [lastBtnArr objectAtIndex:k])
                        {
                            [seleBtn setImage:self.roundSelect forState:UIControlStateNormal];
                            NSDictionary *dic =@{@"childId": [NSString stringWithFormat:@"%d",childIdNum],@"isNormal":[NSString stringWithFormat:@"%d",k],@"childRemark":childRemark};
                            checkIdIndex = [self indexOfObject:[NSString stringWithFormat:@"%i",childIdNum] Array:childIds];
                            childIdIndex = [childIds[checkIdIndex] indexOfObject:[NSString stringWithFormat:@"%i",childIdNum]];
                            [sendChildDatas replaceObjectAtIndex:childIdIndex withObject:dic];
                            [self.sendCheckDatas replaceObjectAtIndex:checkIdIndex withObject:@{@"checkId": checkId,@"childData":sendChildDatas}];
                        }
                        if (j == 0)
                        {
                            [[UIApplication sharedApplication].keyWindow endEditing:YES];
                        }
                    }
                }
            }
        }
    }
}
- (int)indexOfObject:(id)object Array:(NSArray *)array
{
    for (int i = 0; i < array.count; i ++)
    {
        if ([array[i] containsObject:object])
        {
            return i;
        }
    }
    return 0;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
